package com.naiterui.ehp.bs.payment.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.naiterui.ehp.bp.support.advice.IgnoreResponseEntityWrap;
import com.naiterui.ehp.bs.payment.exception.ExceptionCodes;
import com.naiterui.ehp.bs.payment.exception.PaymentBusinessException;
import com.naiterui.ehp.bs.payment.service.IOrderService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 支付回调接口
 * 具体接口请看接口注释
 *
 * @date 2017年09月09日
 * @since 1.0.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(value = "支付回调接口")
public class NotifyController {

    private final IOrderService orderService;

    /**
     * 支付回调接口
     *
     * @param channelInfoId 支付账号
     *
     * @return 对应渠道所需信息
     *
     * @date 2017年09月09日
     * @since 1.0.0
     */
    @ApiOperation(value = "支付回调接口网关")
    @PostMapping("/callback/")
    @IgnoreResponseEntityWrap
    @ApiImplicitParams({@ApiImplicitParam(required = true, dataType = "xml", paramType = "body")})
    public String callBack(@RequestBody String xml) throws PaymentBusinessException, WxPayException {
        if (StringUtils.isBlank(xml)) {
            throw new PaymentBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        // 使用策略模式创建对应的支付回调
        log.info("支付回调通知 回调数据:{} ", xml);
        this.orderService.notify(xml);
        return WxPayNotifyResponse.success("");
    }

}
